import { defineStore } from 'pinia';
import { pageSizes } from '@/enums/baseConstant';
import { storeMessage } from '@/utils/message';
import {
  fetchCreateKnowledge,
  fetchDeleteKnowledge,
  fetchGetKnowledgeDetail,
  fetchGetKnowledgeList,
  fetchGetKnowledgeByCourse,
  fetchUpdateKnowledge,
  fetchGetKnowledgePrerequisites,
  fetchUpdateKnowledgePrerequisites,
  fetchGetKnowledgeTree,
  KnowledgeQueryParams,
  KnowledgeTreeVO
} from '@/api/kg/knowledge';
import { fetchGetCourseOptions } from '@/api/kg/course';

/**
 * 知识点信息 Store
 */
export const useKnowledgeStore = defineStore('knowledgeStore', {
  state() {
    return {
      // 知识点信息列表
      datalist: [],
      // 课程列表
      courseList: [],
      // 当前选中的课程ID
      selectedCourseId: undefined as string | undefined,
      // 常用标签列表
      commonTags: ['基础概念', '核心知识', '高级应用', '实践案例', '扩展知识'],
      // 查询表单
      form: {
        // 知识点名称
        name: undefined,
        // 知识点概述
        summary: undefined,
        // 知识点难度级别
        level: undefined,
        // 所属课程ID
        courseId: undefined,
        // 标签
        tags: undefined,
      },
      // 分页查询结果
      pagination: {
        currentPage: 1,
        pageSize: pageSizes[0],
        total: 0,
        pageSizes,
      },
      // 加载
      loading: false,
    };
  },
  getters: {},
  actions: {
    /** 设置当前选中课程 */
    setSelectedCourse(courseId: string | undefined) {
      this.selectedCourseId = courseId;
      this.form.courseId = courseId;
    },

    /** 获取课程列表 */
    async getCourseList() {
      const result = await fetchGetCourseOptions();
      if (result.code === 200) {
        this.courseList = result.data || [];
        return result.data;
      }
      return [];
    },

    /** 获取知识点列表（带分页和搜索） */
    async getKnowledgeList() {
      this.loading = true;
      try {
        // 整理请求参数
        const params: KnowledgeQueryParams = {
          ...this.form,
          currentPage: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };

        // 过滤掉undefined的属性
        Object.keys(params).forEach(key => {
          if (params[key as keyof KnowledgeQueryParams] === undefined) {
            delete params[key as keyof KnowledgeQueryParams];
          }
        });

        const result = await fetchGetKnowledgeList(params);
        if (result.code === 200) {
          this.datalist = result.data.list || [];
          this.pagination.total = result.data.total;
          this.pagination.currentPage = result.data.pageNo;
          this.pagination.pageSize = result.data.pageSize;
          return result.data.list;
        }
        return [];
      } finally {
        this.loading = false;
      }
    },

    /** 获取课程的所有知识点 */
    async getKnowledgeByCourse(courseId: string) {
      const result = await fetchGetKnowledgeByCourse(courseId);
      if (result.code !== 200) return [];
      return result.data;
    },

    /** 获取知识点详情 */
    async getKnowledgeDetail(id: string) {
      const result = await fetchGetKnowledgeDetail(id);
      if (result.code !== 200) return null;
      return result.data;
    },

    /** 创建知识点 */
    async createKnowledge(courseId: string, data: any) {
      const result = await fetchCreateKnowledge(courseId, data);
      return storeMessage(result);
    },

    /** 更新知识点信息 */
    async updateKnowledge(id: string, data: any) {
      const result = await fetchUpdateKnowledge(id, data);
      return storeMessage(result);
    },

    /** 删除知识点 */
    async deleteKnowledge(id: string) {
      const result = await fetchDeleteKnowledge(id);
      return storeMessage(result);
    },

    /** 获取知识点的前置知识点列表 */
    async getKnowledgePrerequisites(knowledgeId: string) {
      const result = await fetchGetKnowledgePrerequisites(knowledgeId);
      if (result.code !== 200) return [];
      return result.data;
    },

    /** 更新知识点的前置知识点列表 */
    async updateKnowledgePrerequisites(knowledgeId: string, preKnowledgeIds: string[]) {
      const result = await fetchUpdateKnowledgePrerequisites(knowledgeId, preKnowledgeIds);
      return storeMessage(result);
    },

    /** 重置表单 */
    resetForm() {
      this.form = {
        name: undefined,
        summary: undefined,
        level: undefined,
        courseId: this.selectedCourseId,
        tags: undefined,
      };
      this.pagination.currentPage = 1;
      this.pagination.pageSize = pageSizes[0];
    },

    /** 获取知识点树形结构数据 */
    async getKnowledgeTree(excludeKnowledgeId?: string) {
      const result = await fetchGetKnowledgeTree(excludeKnowledgeId);
      if (result.code === 200) {
        return result.data || [];
      }
      return [];
    }
  },
});
